package fun.tan90.easy.binlog.plugin.redis.sentinel.service.impl;


import cn.hutool.json.JSONUtil;
import fun.tan90.easy.binlog.plugin.redis.common.constants.RedisPluginConstants;
import fun.tan90.easy.binlog.plugin.redis.sentinel.model.RedisSentinelParams;
import fun.tan90.easy.binlog.plugin.common.service.PluginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.time.Duration;
import java.util.Set;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/11/15 14:41
 */
@Slf4j
public class RedisSentinelPluginService implements PluginService {

    @Override
    public boolean test(String params) {
        RedisSentinelParams redisSentinelParams = JSONUtil.toBean(params, RedisSentinelParams.class);
        // 创建连接池配置对象
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMinIdle(redisSentinelParams.getMinIdle());   // 设置最小空闲连接数
        poolConfig.setMaxIdle(redisSentinelParams.getMaxIdle());   // 设置最大空闲连接数
        poolConfig.setMaxTotal(redisSentinelParams.getMaxTotal()); // 设置最大连接数
        poolConfig.setMaxWait(Duration.ofMillis(redisSentinelParams.getMaxWait()));   // 设置从连接池获取连接的最大等待时间

        String masterName = redisSentinelParams.getMasterName();
        Set<String> sentinels = redisSentinelParams.getSentinels();
        int timeout = redisSentinelParams.getTimeout();
        int soTimeout = RedisPluginConstants.SO_TIMEOUT;
        String user = StringUtils.hasLength(redisSentinelParams.getUser()) ? redisSentinelParams.getUser() : null;
        String password = StringUtils.hasLength(redisSentinelParams.getPassword()) ? redisSentinelParams.getPassword() : null;
        int database = redisSentinelParams.getDatabase();
        try (JedisSentinelPool jedisSentinelPool = new JedisSentinelPool(masterName, sentinels, poolConfig, timeout, soTimeout, user, password, database, "eb_redis_sentinel")) {
            try (Jedis jedis = jedisSentinelPool.getResource()) {
                return "PONG".equals(jedis.ping());
            } catch (Exception e) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }
}
